import sev from "../service.js"
import store from "../store/index.js"   
let baseUrl = 'http://localhost:18080';  
const soketUrl = ''; 
const ajax = (opt) => {
	const userToken = sev.getUsers('userInfo').accessToken
	const userId = sev.getUsers('userInfo').userId
	opt = opt || {};
	if (opt.isToken) {
		if(!userToken){
			uni.navigateTo({
				url:'/pages/my/my-index/login/login'
			})
			return false
		}
		if (!opt.header) {
			opt.header = {
				"lang": "cn"
			}
		}
	
		opt.header.accessToken = userToken
		opt.header.userId = userId
	}

	opt.url = opt.url || '';
	opt.data = opt.data || null;
	opt.method = opt.method || 'GET';
	opt.header = opt.header || {
		"lang": "cn",
		// "Access-Control-Allow-Credentials":"false"
	};
	
	opt.success = opt.success || function() {};

	uni.request({
		url: baseUrl + opt.url,
		data: opt.data,
		method: opt.method,
		header: opt.header,
		dataType: 'json',
		success: function(res) {
			if (opt.isToken) {
				if (res.data.code == -1) {
					store.commit('logout')
					uni.showModal({
						title: '登录失效',
						content: '登录失效，需要重新登录后才能继续', 
						showCancel: true,
						success: (res) => {
							if (res.confirm) {
								uni.navigateTo({ url: '/pages/my/my-index/login/login' });
							}  
						}
					});
					uni.removeStorage({ key: 'userInfo',  });
					return false
				}
			}
			
			opt.success(res);
		},
		fail: function() {
			if(opt.fail){
					opt.fail();
			} else {
				// uni.showToast({
				// 	title: '请求超时',
				// 	icon: "none"
				// });
			}
		}
	})
}

export default {
	ajax,
	baseUrl,
	soketUrl
}
